<template>
  <div class="budget-page">
    <div class="page-header">
      <div class="page-title">造价审核</div>
    </div>



    <template v-if="currentStep === 0">
        <div style="margin-bottom:20px ;">
            <el-button @click="bindExamine" type="success">造价审核上传</el-button>
            <el-button @click="downloadTpl" type="primary">下载</el-button>
        </div>
    
      <div class="complete-container">
        <div class="detail-table">
          <h2 class="table-title">工程项目成本预算明细表</h2>

          <div class="project-info">
            <span>项目名称：{{costInfo.project?.projectName}}</span>
            <span class="unit-label">(单位：元)</span>
          </div>

          <el-table :data="confirmTableData" border :span-method="objectSpanMethod">
            <el-table-column prop="name1" label="明细" width="60"></el-table-column>
            <el-table-column prop="name2" label="" width="80"></el-table-column>
            <el-table-column prop="name" label=""></el-table-column>
            <el-table-column prop="sequence" label="项次" width="80" align="center" />
            <el-table-column prop="budgetAmount" label="金额" width="180" align="right">
              <template #default="scope">
                <span :class="{ 'blue-text': scope.row.isBlue }">{{ costInfo[scope.row.budgetAmount] }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="auditAmount" label="审核金额" width="180" align="right">
              <template #default="scope">
                <span>{{ costInfo[scope.row.auditAmount] || '0.00' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </template>
        <!-- 步骤指示器 -->
        <div class="step-container" v-if="currentStep != 0">
      <el-steps :active="currentStep" simple>
        <el-step title="数据录入" />
        <el-step title="附件上传" />
        <el-step title="数据确认" />
      </el-steps>
    </div>

    <!-- 根据当前步骤显示不同的内容 -->
    <div v-if="currentStep === 1">
      <div class="form-container">
        <el-form ref="budgetForm" :model="formData" label-position="right" label-width="280px">
          <div class="currency-label">(单位：元)</div>

          <div class="form-content">
            <!-- 原始数据列 -->
            <div class="form-column">
              <div class="column-title">预算金额</div>
              <el-form-item v-for="(item, index) in formItems" :key="index" :label="item.label">
                <el-input v-model="formData[item.prop]" :placeholder="'输入' + item.label" class="budget-input" disabled />
              </el-form-item>
            </div>

            <!-- 审核金额列 -->
            <div class="form-column">
              <div class="column-title">审核金额</div>
              <el-form-item v-for="(item, index) in formItems" :key="index">
                <el-input v-model="formData[item.auditProp]" :placeholder="'请输入审核金额'" class="budget-input">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </div>
          </div>
        </el-form>

        <!-- 底部按钮 -->
        <div class="form-footer">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
      </div>
    </div>

    <div v-if="currentStep === 2" class="upload-container">
      <!-- 预算明细选项卡 -->
      <div class="budget-tabs">
        <ProjectTabsCost ref="childRef" :projectId="projectId" :costId="costId" :formData="formData" />
      </div>

      <!-- 底部按钮 -->
      <div class="form-footer">
        <el-button @click="prevStep">上一步</el-button>
        <el-button type="primary" @click="nextStep">下一步</el-button>
      </div>
    </div>

    <!-- 第三步：数据确认 -->
    <div v-if="currentStep === 3" class="confirm-container">
      <div class="detail-table">
        <h2 class="table-title">工程项目成本预算明细表</h2>

        <div class="project-info">
          <span>项目名称：{{costInfo.project?.projectName}}</span>
          <span class="unit-label">(单位：元)</span>
        </div>

        <el-table :data="confirmTableData" :span-method="objectSpanMethod" border>
          <!-- <el-table-column prop="name" label="明细" />
          <el-table-column prop="sequence" label="项次" width="100" align="center" />
          <el-table-column prop="budgetAmount" label="预算金额(元)" width="200" align="right">
            <template #default="scope">
              <span :class="{ 'blue-text': scope.row.isBlue }">{{ formData[scope.row.budgetAmount]}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="auditAmount" label="审核金额" width="200" align="right">
            <template #default="scope">
              <span :class="{ 'blue-text': scope.row.isBlue }">{{ formData[scope.row.auditAmount]}}</span>
            </template>        
            </el-table-column> -->
            <el-table-column prop="name1" label="明细" width="60"></el-table-column>
            <el-table-column prop="name2" label="" width="80"></el-table-column>
            <el-table-column prop="name" label=""></el-table-column>
            <el-table-column prop="sequence" label="项次" width="80" align="center" />
            <el-table-column prop="budgetAmount" label="金额" width="180" align="right">
              <template #default="scope">
                <span :class="{ 'blue-text': scope.row.isBlue }">{{ costInfo[scope.row.budgetAmount] }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="auditAmount" label="审核金额" width="180" align="right">
              <template #default="scope">
                <span>{{ costInfo[scope.row.auditAmount] || '0.00' }}</span>
              </template>
            </el-table-column>
       
        </el-table>
      </div>

      <!-- 底部按钮 -->
      <div class="form-footer">
        <el-button @click="prevStep">上一步</el-button>
        <el-button type="primary" @click="nextStep">确认并完成</el-button>
      </div>
    </div>

    <!-- 第四步：完成 -->
    <!-- <div v-if="currentStep === 4" class="complete-container">
        <div class="detail-table">
          <h2 class="table-title">工程项目成本预算明细表</h2>
          
          <div class="project-info">
            <span>项目名称：2021年度机电系统养护工程项目</span>
            <span class="unit-label">(单位：元)</span>
          </div>
  
          <el-table :data="confirmTableData" border>
            <el-table-column prop="name" label="明细" min-width="300" />
            <el-table-column prop="sequence" label="项次" width="80" align="center" />
            <el-table-column prop="budgetAmount" label="预算金额" width="180" align="right">
              <template #default="scope">
                <span :class="{ 'blue-text': scope.row.isBlue }">{{ scope.row.budgetAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="auditAmount" label="审核金额" width="180" align="right">
              <template #default="scope">
                <span>{{ formData[scope.row.auditAmount] || '0.00' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div> -->
  </div>
</template>
  
  <script>
import ProjectTabsCost from "../cost/ProjectTabsCost"
import projectCostService from '@/api/cost/projectCostService'
import { ElNotification, ElMessageBox } from "element-plus";
export default {
  name: 'Budget',
  components: { ProjectTabsCost },
  data() {
    return {
      projectId: '',
      basisType: '',
      currentStep: 0,
      formData: {
        unForeseenExpenses: '',
        winningServiceFee: '',
        biddingDocumentFee: '',
        engineeringInsurance: '',
        personnelManagementFee: '',
        taxes: '',
        auditUnForeseenExpenses: '',
        auditWinningServiceFee: '',
        auditBiddingDocumentFee: '',
        auditEngineeringInsurance: '',
        auditPersonnelManagementFee: '',
        auditTaxes: '',
        auditEquipmentCost: '',
        auditConstructionCost: '',
        auditSafetyProductionCost: '',
        auditResearchFunding: '',
        auditOtherManagementFee: '',
        auditMiscellaneous: ''
      },
      tableData: [],
      confirmTableData: [
        { name1: '一、有效合同额（1项=2项-3项）', sequence: '1', budgetAmount: 'contractAmount', auditAmount: 'auditContractAmount' },
        { name1: '合同总额', sequence: '2', budgetAmount: 'contractAmount', auditAmount: 'auditContractAmount' },
        { name1: '减：不可预见费', sequence: '3', budgetAmount: 'unForeseenExpenses', auditAmount: 'auditUnForeseenExpenses' },
        { name1: '二、项目直接成本（4项=7项+17项）', sequence: '4', budgetAmount: 'directCost', auditAmount: 'auditDirectCost' },
        { name2: '中标服务费', sequence: '5', budgetAmount: 'winningServiceFee', auditAmount: 'auditWinningServiceFee', rowType: 'bidding', name1: '投标阶段' },
        { name2: '标书制作费（标书文件费、公证费等）', sequence: '6', budgetAmount: 'biddingDocumentFee', auditAmount: 'auditBiddingDocumentFee', rowType: 'bidding', name1: '投标阶段' },
        { name2: '小计：（7项=5项+6项）', sequence: '7', budgetAmount: 'subtotal1', auditAmount: 'auditSubtotal1', rowType: 'bidding', name1: '投标阶段' },

        { name2: '附表一：设备（材料、软件）费', sequence: '8', budgetAmount: 'equipmentCost', auditAmount: 'auditEquipmentCost', rowType: 'construction', name1: '施工阶段' },
        { name2: '附表二：施工（服务）费', sequence: '9', budgetAmount: 'constructionCost', auditAmount: 'auditConstructionCost', rowType: 'construction', name1: '施工阶段' },
        { name2: '工程保险费（工程一切险、第三方责任险、意外伤害险等）', sequence: '10', budgetAmount: 'engineeringInsurance', auditAmount: 'auditEngineeringInsurance', rowType: 'construction', name1: '施工阶段' },
        { name2: '安全生产费、保通费等', sequence: '11', budgetAmount: 'safetyProductionCost', auditAmount: 'auditSafetyProductionCost', rowType: 'construction', name1: '施工阶段' },
        { name2: '科研费', sequence: '12', budgetAmount: 'researchFunding', auditAmount: 'auditResearchFunding', rowType: 'construction', name1: '施工阶段' },
        // { name2: '分公司管理费', sequence: '', budgetAmount: '', auditAmount: '', isSubPhase: true, rowType: 'management', name1: '施工阶段' },
        { name: '人员管理费：（13项=1%*国定浮调比例）', sequence: '13', budgetAmount: 'personnelManagementFee', auditAmount: 'auditPersonnelManagementFee', rowType: 'management', name1: '施工阶段', name2: '分公司管理费' },
        { name: '其他管理费（房屋租赁、车辆使用租赁费用、办公经费等）', sequence: '14', budgetAmount: 'otherManagementFee', auditAmount: 'auditOtherManagementFee', rowType: 'management', name1: '施工阶段', name2: '分公司管理费' },
        { name2: '其他（高空车、吊车等机械设备租赁）', sequence: '15', budgetAmount: 'miscellaneous', auditAmount: 'auditMiscellaneous', rowType: 'construction', name1: '施工阶段' },
        { name2: '税金', sequence: '16', budgetAmount: 'taxes', auditAmount: 'auditTaxes', rowType: 'construction', name1: '施工阶段' },
        { name2: '小计（17项=SUM(8项:16项)-12项）', sequence: '17', budgetAmount: 'subtotal2', auditAmount: 'auditSubtotal2', rowType: 'construction', name1: '施工阶段' },
        { name1: '三、项目利润：18项=1项-4项', sequence: '18', budgetAmount: 'profit', auditAmount: 'auditProfit' },
        { name1: '四、项目利润率：（19项=18项/1项*100%）', sequence: '19', budgetAmount: 'profitRate', auditAmount: 'auditProfitRate' }
      ],
      formItems: [
        {
          label: '不可预见费',
          prop: 'unForeseenExpenses',
          auditProp: 'auditUnForeseenExpenses'
        },
        {
          label: '中标服务费',
          prop: 'winningServiceFee',
          auditProp: 'auditWinningServiceFee'
        },
        {
          label: '标书制作费（标书文件费、公证费等）',
          prop: 'biddingDocumentFee',
          auditProp: 'auditBiddingDocumentFee'
        },
        {
          label: '工程保险费（工程一切险、第三方责任险、意外伤害险等）',
          prop: 'engineeringInsurance',
          auditProp: 'auditEngineeringInsurance'
        },
        {
          label: '人员管理费：（13项=1%*国定浮调比例）',
          prop: 'personnelManagementFee',
          auditProp: 'auditPersonnelManagementFee'
        },
        {
          label: '税金',
          prop: 'taxes',
          auditProp: 'auditTaxes'
        }
      ],
      costInfo: {},
      costId:'',
      info: {

      }
    }
  },
  created() {
    const { id, basisType,costId } = this.$route.query
   
    if(costId){
        this.costId= costId;
      
        this.getCostInfo()
    }

    if (basisType) {
      this.basisType = basisType
    }

    console.log('当前projectId:', this.projectId)
    console.log('当前basisType:', this.basisType)

   
  },
  methods: {
    getInfo() {
      projectCostService.queryById(this.projectId).then(res => {
        this.formData = res;
        if (this.formData.costId) {
          this.getCostInfo()
        }

      })
    },
    getCostInfo() {
      projectCostService.queryById(this.costId).then(res => {
        this.costInfo = res;
        this.formData = res;
        this.projectId=res.project.projectId
      })
    },
    bindExamine() {
      this.currentStep = 1;
    },
    async nextStep() {
      if (this.currentStep === 2) {
        // try {
        //   const resone = await this.$refs.childRef.nextCost();
        //   this.formData = resone
        //   this.updateConfirmTableData();
        //   this.currentStep++;
        // } catch (error) {
        //   console.error('提交失败:', error);
        //   this.$message.error('提交失败，请重试');
        // }

        try {
          // 弹出确认提示
          await ElMessageBox.confirm('确认该页面已完成，进入下一步操作？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });

          // 获取子组件的 inputForm 数据
          const inputFormData = this.$refs.childRef.getInputFormData();
    

          // 保存步骤2的数据
          this.savedFormData = { ...this.formData, ...inputFormData };

          // 如果用户确认，继续执行下一步操作
          const resone = await this.$refs.childRef.nextCost();
          this.formData = resone;
          this.updateConfirmTableData();
          this.currentStep++;
        } catch (error) {
          // 用户取消或发生错误时的处理
          console.error('操作取消或失败:', error);
          this.$message.info('操作已取消');
        }
      } else if (this.currentStep === 3) {
        // 提交所有数据
        this.saveSubmit();

      } else if (this.currentStep < 4) {
        this.currentStep++;
      }
    },
    prevStep() {
      if (this.currentStep > 0) {
        this.currentStep--
      }
    },
    // 表单提交
    saveSubmit() {

      try {

     
        this.loading = true;
        // this.inputForm.project.id = this.projectId;
        // this.inputForm = { ...this.inputForm, ...this.formData }

        projectCostService.save({ ...this.formData, project: { id: this.formData.project.id },isSubmit:1 }).then((data) => {
          this.loading = false
          this.$message.success('保存成功');
          this.returnToProjectDetails()
          this.currentStep = 0
        }).catch((error) => {
          this.loading = false
          this.$message.error('提交失败，请重试');
        })
      } catch (error) {
        this.loading = false
        this.$message.error('提交失败，请重试');
      }
    },

    updateConfirmTableData() {
      // 格式化数字显示
      // this.confirmTableData = this.confirmTableData.map(item => ({
      //   ...item,
      //   budgetAmount: this.formatNumber(item.budgetAmount)
      // }));
    },
    formatNumber(value) {
      // 移除非数字字符（保留小数点）
      value = value.toString().replace(/[^\d.]/g, '');
      // 保留两位小数
      const num = parseFloat(value);
      return isNaN(num) ? '' : num.toFixed(2);
    },
    handleAuditInput(item) {
      const value = this.formData[item.auditProp];
      // 可以在这里添加数字格式化或其他处理逻辑
      if (value) {
        this.formData[item.auditProp] = this.formatNumber(value);
      }
    },
    async submitAllData() {
      // 这里处理最终的数据提交
      const submitData = {
        ...this.formData,
        // 可以添加其他需要提交的数据
      };
      // 调用API提交数据

      console.log("tijiao", this.$refs.childRef)



    },
    returnToProjectDetails() {
      this.$router.push({
        path: '/cost/ProjectCostList',
      })
    },
    returnToList() {
      this.$router.push('/project/ProjectMainList')
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {

      // 处理投标阶段合并
      if (rowIndex <= 3 || rowIndex > 16) {
        if (columnIndex == 0) {
          return [1, 3];
        } else if (columnIndex == 1 || columnIndex == 2) {
          return [0, 0];
        }
      } else if (rowIndex > 3 && rowIndex <= 6) {
        if (columnIndex == 0 && rowIndex == 4) {
          return [3, 1];
        } else if (columnIndex == 0 && rowIndex == 5) {
          return [0, 0];
        } else if (columnIndex == 0 && rowIndex == 6) {
          return [0, 0];
        } else if (columnIndex == 1) {
          return [1, 2];
        } else if (columnIndex == 2) {
          return [0, 0];
        }
      } else if (rowIndex > 6 && rowIndex <= 16) {
        if (columnIndex == 0 && rowIndex == 7) {
          return [10, 1];
        } else if (columnIndex == 0 && rowIndex <= 16) {
          return [0, 0];
        } else if (columnIndex == 1 && rowIndex != 12 && rowIndex != 13) {
          return [1, 2];
        } else if (columnIndex == 2 && rowIndex != 12 && rowIndex != 13) {
          return [0, 0];
        } else if (columnIndex == 1 && rowIndex == 12) {
          return [2, 1];
        } else if (columnIndex == 1 && rowIndex == 13) {
          return [0, 0];
        }
      }


    },
    downloadTpl() {
      this.loading = true
      projectCostService
        .exportFinally({ id: this.formData.id })
        .then((data) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, "成本预算表");
          this.loading = false
        })
        .catch(function (err) {
          this.loading = false
          if (err.response) {
            console.log(err.response);
          }
        });
    },


  }
}
  </script>
  
  <style scoped lang="scss">
.budget-page {
  padding: 20px;
  background: #fff;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .page-title {
    font-size: 16px;
    font-weight: bold;
  }

  .step-container {
    margin: 20px 0 40px;
    padding: 20px;
    background: #f5f7fa;
  }

  .form-container {
    padding: 0 20px;
    max-width: 1000px;
    margin: 0 auto;

    .currency-label {
      color: #909399;
      font-size: 14px;
      text-align: center;
      margin-bottom: 30px;
    }

    .form-content {
      display: flex;
      gap: 40px;

      .form-column {
        flex: 1;

        .column-title {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 20px;
          padding-left: 20px;
          border-left: 4px solid #409eff;
          line-height: 20px;
        }

        &:first-child {
          :deep(.el-input__inner) {
            background-color: #f5f7fa;
            color: #909399;
          }
        }
      }
    }

    .budget-input {
      width: 100%;

      :deep(.el-input__inner) {
        text-align: right;
        padding-right: 8px;
      }

      :deep(.el-input-group__append) {
        padding: 0 8px;
      }
    }

    .el-form-item {
      margin-bottom: 25px;

      :deep(.el-form-item__label) {
        font-weight: normal;
        color: #606266;
        text-align: right;
      }

      :deep(.el-form-item__content) {
        margin-left: 0 !important;
      }
    }
  }

  .form-footer {
    margin-top: 40px;
    text-align: center;

    .el-button {
      padding: 12px 25px;
      margin: 0 10px;
    }
  }

  .upload-container {
    // padding: 0 20px;

    .budget-tabs {
      margin-bottom: 20px;

      :deep(.el-tabs__item) {
        height: 40px;
        line-height: 40px;
        font-size: 14px;

        .el-icon-document {
          margin-right: 5px;
        }
      }
    }

    .operation-buttons {
      margin-bottom: 20px;

      .el-button {
        margin-right: 10px;
      }
    }

    :deep(.el-table) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: normal;
      }

      td {
        padding: 8px 0;
      }
    }
  }

  .confirm-container {
    padding: 0 20px;
    max-width: 1200px;
    margin: 0 auto;

    .detail-table {
      background: #f2f4f5;
      padding: 30px;
      border-radius: 4px;

      .table-title {
        text-align: center;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
      }

      .project-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        padding: 0 10px;

        .unit-label {
          color: #909399;
        }
      }

      :deep(.el-table) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: normal;
        }

        td {
          background-color: #f2f4f5;
        }

        .blue-text {
          color: #409eff;
        }

        .el-input {
          .el-input__inner {
            text-align: right;
            padding-right: 8px;
            // background-color: #F2F4F5;
          }

          &.blue-input {
            .el-input__inner {
              color: #409eff;
            }
          }
        }

        .el-input-group__append {
          padding: 0 8px;
          background-color: #f2f4f5;
          color: #909399;
        }
      }
    }
  }

  .complete-container {
    padding: 0 20px;
    max-width: 1200px;
    margin: 0 auto;

    .detail-table {
      background: #f2f4f5;
      padding: 30px;
      border-radius: 4px;

      .table-title {
        text-align: center;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
      }

      .project-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        padding: 0 10px;

        .unit-label {
          color: #909399;
        }
      }

      :deep(.el-table) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: normal;
        }

        td {
          background-color: #f2f4f5;
        }

        .blue-text {
          color: #409eff;
        }

        .el-input {
          .el-input__inner {
            text-align: right;
            padding-right: 8px;
            // background-color: #F2F4F5;
          }

          &.blue-input {
            .el-input__inner {
              color: #409eff;
            }
          }
        }

        .el-input-group__append {
          padding: 0 8px;
          background-color: #f2f4f5;
          color: #909399;
        }
      }
    }
  }
}
</style>
  